package step5;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * Thread 생성시에 객체로 사용될 클래스 
 * 실제 클라이언트와 통신을 담당한다. 
 * 통신하기 위해서는 socket 이 필요하다. 
 * 
 * 생성자 
 * Socket을 할당받는 생성자 명시 
 * 
 * 멤버변수
 * Socket
 * BufferedReader
 * PrintWriter
 * 
 * 멤버메서드 
 * run()
 * echo() : 통신 
 * closeAll() 
 * 개발 step
 * echo() 
 * 1. BufferedReader>InputStreamReader>socket.getInputStream()
 * 2. PrintWriter>socket.getOutputStream()
 * 3. while(true)
 * 4. readLine()
 * 5. null 비교해서 break
 * 6. println()
 * 7. finally 블럭에서 closeAll() 
 * @author kosta-00-kangsa-001
 *
 */
public class ServerWorker implements Runnable{
	private Socket socket;
	private BufferedReader br;
	private PrintWriter pw;
	public ServerWorker(Socket socket) {
		this.socket=socket;
	}
	public void echo() throws IOException{
		br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
		pw=new PrintWriter(socket.getOutputStream(),true);
		String user=socket.getInetAddress().toString();
		while(true){
			String mess=br.readLine();
			if(mess==null){				
				System.out.println("["+user+"]님이 나가셨습니다...TT");
				break;
			}
			System.out.println(user+"님의 메세지:"+mess);
			pw.println(mess+" server~~~*");
		}
	}
	public void closeAll() throws IOException{
		if(pw!=null)
			pw.close();
		if(br!=null)
			br.close();
		if(socket!=null)
			socket.close();
	}
	@Override
	public void run() {
		try {
			echo();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				closeAll();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}




